/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClienteDialog.java
 *
 * Created on 01/03/2012, 16:50:54
 */
package br.com.mocamorena.view.dialog;

import br.com.mocamorena.control.ControleCliente;
import br.com.mocamorena.exception.InputValidationException;
import br.com.mocamorena.exception.PersistenciaException;
import br.com.mocamorena.model.Cliente;
import br.com.mocamorena.model.Telefone;
import br.com.mocamorena.model.constant.Natureza;
import br.com.mocamorena.view.ErrorsList;
import br.com.mocamorena.view.StateEntityWindow;
import br.com.mocamorena.view.UserError;
import br.com.mocamorena.view.UtilitiesGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class ClienteDialog extends javax.swing.JDialog {

    private Cliente cliente;
    private final static String titleWindow = "Cliente";
    private StateEntityWindow stateEntity;

    public ClienteDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Cliente cliente) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setCliente(cliente);
        organizeWindow();
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cabecalhoPanel = new br.com.mocamorena.view.panel.CabecalhoPanel();
        jLabel1 = new javax.swing.JLabel();
        naturezaCombo = new javax.swing.JComboBox();
        entidadePanel = new br.com.mocamorena.view.panel.PanelEntidade();
        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        enderecoPanel = new br.com.mocamorena.view.panel.EnderecoPanel();
        telefonesPanel = new br.com.mocamorena.view.panel.TelefonesPanel();
        observacaoPanel = new br.com.mocamorena.view.panel.ObservacaoPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Natureza:");

        UtilitiesGUI.respondToArrowEnterKey(naturezaCombo);
        naturezaCombo.setModel(new DefaultComboBoxModel(Natureza.values()));
        naturezaCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                naturezaComboItemStateChanged(evt);
            }
        });

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(57, 57, 57)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(naturezaCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(217, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 585, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(123, 123, 123)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addContainerGap(262, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(24, Short.MAX_VALUE)
                .addComponent(entidadePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 561, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(enderecoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(33, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(telefonesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addComponent(observacaoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 565, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(naturezaCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(entidadePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(enderecoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(telefonesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(observacaoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void naturezaComboItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_naturezaComboItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            entidadePanel.getCardLayout().show(entidadePanel, ((Natureza) naturezaCombo.getSelectedItem()).name());
            
        }
    }//GEN-LAST:event_naturezaComboItemStateChanged

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            ControleCliente controle = new ControleCliente();
            Cliente cliente = getCliente();
            if (getStateEntity() == StateEntityWindow.NEW) {
                controle.inserir(cliente);
            } else if (getStateEntity() == StateEntityWindow.UPDATE) {
                controle.atualizar(cliente);
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
    }//GEN-LAST:event_confirmarButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ClienteDialog dialog = new ClienteDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private br.com.mocamorena.view.panel.CabecalhoPanel cabecalhoPanel;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton confirmarButton;
    private br.com.mocamorena.view.panel.EnderecoPanel enderecoPanel;
    private br.com.mocamorena.view.panel.PanelEntidade entidadePanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JComboBox naturezaCombo;
    private br.com.mocamorena.view.panel.ObservacaoPanel observacaoPanel;
    private br.com.mocamorena.view.panel.TelefonesPanel telefonesPanel;
    // End of variables declaration//GEN-END:variables

    private Cliente getCliente() {
        if (cliente == null) {
            cliente = new Cliente();
        }
        cliente.setBloqueado(cabecalhoPanel.isBloqueado());
        cliente.setNatureza((Natureza)naturezaCombo.getSelectedItem());
        if (((Natureza) naturezaCombo.getSelectedItem()).equals(Natureza.FISICA)) {
            entidadePanel.getPessoaFisicaPanel().fillEntity(cliente);
        } else if (((Natureza) naturezaCombo.getSelectedItem()).equals(Natureza.JURIDICA)) {
            entidadePanel.getPessoaJuridicaPanel().fillEntity(cliente);
        }
        cliente.setEndereco(enderecoPanel.getEndereco());
        cliente.setTelefonesList(telefonesPanel.getTelefonesList());
        cliente.setObservacao(observacaoPanel.getObservacao());
        return cliente;
    }

    private void setCliente(Cliente cliente) {
        if(cliente == null) {
            return;
        }
        this.cliente = cliente;
        cabecalhoPanel.setCodigo(cliente.getId());
        cabecalhoPanel.setBloqueado(cliente.isBloqueado());
        naturezaCombo.setSelectedItem(cliente.getNatureza());
        if(cliente.getNatureza().equals(Natureza.FISICA)) {
            entidadePanel.getPessoaFisicaPanel().fillPanel(cliente);
        } else if(cliente.getNatureza().equals(Natureza.JURIDICA)) {
            entidadePanel.getPessoaJuridicaPanel().fillPanel(cliente);
        }
        enderecoPanel.setEndereco(cliente.getEndereco());
        telefonesPanel.setTelefonesList(cliente.getTelefonesList());
        observacaoPanel.setObservacao(cliente.getObservacao());
    }

    private void organizeWindow() {
        if (getStateEntity() == StateEntityWindow.NEW) {
            cabecalhoPanel.setBloqueado(false);
            cabecalhoPanel.isEnabledComponentBloqueado(false);
            telefonesPanel.setTelefonesList(new ArrayList<Telefone>());
        } else {
            naturezaCombo.setEnabled(false);
        }
        isShowErrorsLabel(false);
    }

    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }

    private void isShowErrorsLabel(boolean show) {
        entidadePanel.getPessoaFisicaPanel().hideErrorsLabels();
        entidadePanel.getPessoaJuridicaPanel().hideErrorsLabels();
        enderecoPanel.getLogradouroErrorLabel().setVisible(show);
    }

    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }

    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (((Natureza) naturezaCombo.getSelectedItem()).equals(Natureza.FISICA)) {
            if (entidadePanel.getPessoaFisicaPanel().getNome().isEmpty()) {
                errorsList.addError(new UserError(entidadePanel.getPessoaFisicaPanel().getNomeErrorLabel(), "O nome do cliente não foi informado."));
            }
        } else {
            if (entidadePanel.getPessoaJuridicaPanel().getRazaoSocial().isEmpty()) {
                errorsList.addError(new UserError(entidadePanel.getPessoaJuridicaPanel().getRazaoSocialErrorLabel(), "A razão social do cliente não foi informada."));
            }
        }
        if (enderecoPanel.getEndereco() == null) {
            errorsList.addError(new UserError(enderecoPanel.getLogradouroErrorLabel(), "O endereço do cliente não foi informado."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }
    
    public Cliente objetoCliente() {
        return cliente;
    }
    
    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
